package com.minelx.woods.task.common;

import com.minelx.landisk.filesystem.Paths;
import com.minelx.landisk.filesystem.core.Directory;
import com.minelx.landisk.filesystem.core.File;
import com.minelx.landisk.filesystem.core.init.OpenPolicy;

import java.util.UUID;

public class TempFile implements AutoCloseable {

	private static final Directory TEMP_FILES_DIRECTORY = Paths.projectRoot().child().dir("temp_files", OpenPolicy.useExistingOrCreateANewOne());

	private final File file;

	private TempFile(String fileName) {
		file = createTempFile(fileName);
	}

	public File file() {
		return file;
	}

	@Override
	public void close() {
		if (file.path().exists()) {
			file.path().correspondingExistence().remove();
		}
	}

	public static TempFile of(String fileName) {
		return new TempFile(fileName);
	}

	public static TempFile random() {
		return TempFile.of(UUID.randomUUID().toString());
	}

	private static File createTempFile(String fileName) {
		return TEMP_FILES_DIRECTORY.child().file(fileName, OpenPolicy.createANewOne());
	}
}